<template>
  <div class="page-container">
    <div class="page-header">
      <h1>회원 목록</h1>
      <p>회원 관리 / 회원 목록</p>
    </div>

    <div class="page-content">
      <!-- 검색 영역 -->
      <el-card class="search-card">
        <div class="search-container">
          <div class="search-left">
            <span class="search-label">전체 회원</span>
          </div>
          <div class="search-right">
            <el-input
              v-model="searchForm.search"
              placeholder="검색어를 입력하세요."
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button type="primary" @click="handleSearch">검색</el-button>
              </template>
            </el-input>
          </div>
        </div>
      </el-card>

      <!-- 사용자 목록 -->
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <span>회원 목록</span>
            <el-button
              type="primary"
              size="small"
              :loading="isExporting"
              @click="handleExportExcel"
            >
              Excel 내보내기
            </el-button>
          </div>
        </template>
        <el-table
          v-loading="loading"
          :data="userList"
          stripe
          style="width: 100%"
          @sort-change="handleSortChange"
        >
          <el-table-column prop="referralCode" label="추천 코드" width="120" />
          <el-table-column prop="entryCode" label="입장 코드" width="100" />
          <el-table-column prop="name" label="이름" width="120" />
          <el-table-column prop="idNumber" label="신분증" width="180" />
          <el-table-column prop="birthDateFirst6" label="생년월일 (6자리)" width="140" />
          <el-table-column label="비밀번호" width="100">
            <template #default>
              <span>코드는 ASCII 형식입니다</span>
            </template>
          </el-table-column>
          <el-table-column label="계좌 정보" width="150">
            <template #default="{ row }">
              <div class="account-info">
                <div>{{ row.withdrawalBank }}</div>
                <div class="account-number">{{ formatAccountNumber(row.withdrawalAccount) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="mobileNumber" label="휴대전화" width="130" />
          <el-table-column label="보유 금액" width="120" align="right">
            <template #default="{ row }">
              <span class="amount">{{ formatAmount(row.balance?.total || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="일일 분배 진행" width="150">
            <template #default="{ row }">
              <div class="distribution-progress">
                <template v-if="row.stakingProgress">
                  <el-progress
                    :percentage="getDistributionPercentage(row)"
                    :stroke-width="8"
                    status="success"
                    :show-text="false"
                  />
                  <span class="distribution-text">{{ formatDistributionProgress(row) }}</span>
                </template>
                <span v-else class="text-muted">데이터 없음</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="등급" width="100">
            <template #default="{ row }">
              <el-tag :type="getTierTagType(row.tier)" size="small">{{ row.tier }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="보유 코인" width="100">
            <template #default="{ row }">
              <el-button type="primary" size="small" plain @click="handleViewCoins(row)">조회</el-button>
            </template>
          </el-table-column>
          <el-table-column label="입출금 기록" width="150">
            <template #default="{ row }">
              <el-button type="primary" size="small" plain @click="handleViewDepositWithdraw(row)">조회</el-button>
            </template>
          </el-table-column>
          <el-table-column label="원본" width="100">
            <template #default="{ row }">
              <el-button type="primary" size="small" plain @click="handleViewOriginal(row)">조회</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="가입 일자" width="180" sortable="custom">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastLoginAt" label="최후 로그인" width="180" sortable="custom">
            <template #default="{ row }">
              <span v-if="row.lastLoginAt">{{ formatDate(row.lastLoginAt) }}</span>
              <span v-else style="color: #909399;">로그인 기록 없음</span>
            </template>
          </el-table-column>
          <el-table-column prop="lastLoginIp" label="최후 로그인 IP" width="150">
            <template #default="{ row }">
              <span v-if="row.lastLoginIp" style="color: #606266;">{{ row.lastLoginIp }}</span>
              <span v-else style="color: #909399;">-</span>
            </template>
          </el-table-column>
          <el-table-column label="작업" width="120" fixed="right">
            <template #default="{ row }">
              <el-dropdown trigger="click">
                <el-button type="primary" size="small" plain>
                  작업 <el-icon><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleViewDetail(row)">
                      상세 보기
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleViewTransactions(row)">
                      거래 기록
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleChangeTier(row)">
                      등급 변경
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleEditInfo(row)">
                      정보 수정
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleToggleStatus(row)">
                      {{ row.status === UserStatus.ACTIVE ? '일시 중지' : '활성화' }}
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleDeleteUser(row)" divided>
                      <span style="color: #f56c6c">사용자 삭제</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 페이지네이션 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 사용자 상세 대화상자 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="사용자 상세"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <div v-if="selectedUser" class="user-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="이름">{{ selectedUser.name }}</el-descriptions-item>
            <el-descriptions-item label="신분증">{{ selectedUser.idNumber }}</el-descriptions-item>
            <el-descriptions-item label="생년월일 (6자리)">
              {{ selectedUser.birthDateFirst6 }}
            </el-descriptions-item>
            <el-descriptions-item label="추천 코드">{{ selectedUser.referralCode || '없음' }}</el-descriptions-item>
          <el-descriptions-item label="상태">
            <el-tag :type="getStatusTagType(selectedUser.status)">{{ getStatusText(selectedUser.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="은행">{{ selectedUser.withdrawalBank }}</el-descriptions-item>
          <el-descriptions-item label="계좌">{{ selectedUser.withdrawalAccount }}</el-descriptions-item>
          <el-descriptions-item label="휴대전화">{{ selectedUser.mobileNumber }}</el-descriptions-item>
          <el-descriptions-item label="가입 시간">{{ formatDate(selectedUser.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="최후 로그인 시간">
            <span v-if="selectedUser.lastLoginAt">{{ formatDate(selectedUser.lastLoginAt) }}</span>
            <span v-else style="color: #909399;">로그인 기록 없음</span>
          </el-descriptions-item>
          <el-descriptions-item label="최후 로그인 IP">
            <span v-if="selectedUser.lastLoginIp">{{ selectedUser.lastLoginIp }}</span>
            <span v-else style="color: #909399;">-</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 持有币对话框 -->
    <el-dialog
      v-model="coinsDialogVisible"
      title="보유 코인"
      width="700px"
    >
      <div v-if="userCoins && selectedUser">
        <h3>{{ selectedUser.name }}님의 보유 자산</h3>

        <!-- KRW 余额 -->
        <el-descriptions :column="1" border style="margin-top: 20px;">
          <el-descriptions-item label="KRW 가용 잔액">
            {{ formatAmount(userCoins.krw.balance) }} KRW
          </el-descriptions-item>
          <el-descriptions-item label="KRW 동결 금액">
            {{ formatAmount(userCoins.krw.frozen) }} KRW
          </el-descriptions-item>
          <el-descriptions-item label="KRW 총 잔액">
            <strong>{{ formatAmount(userCoins.krw.total) }} KRW</strong>
          </el-descriptions-item>
        </el-descriptions>

        <!-- NEAR 质押信息 -->
        <h3 style="margin-top: 30px;">NEAR 스테이킹 정보</h3>
        <el-descriptions :column="1" border style="margin-top: 15px;" v-if="userCoins.staking">
          <el-descriptions-item label="스테이킹 본금">
            {{ userCoins.staking.stakedAmount.toFixed(4) }} NEAR
          </el-descriptions-item>
          <el-descriptions-item label="락정 금액 (추천 보상)">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>{{ userCoins.staking.lockedAmount.toFixed(4) }} NEAR</span>
              <!-- 추천인은 조정 버튼을 볼 수 없습니다 -->
              <el-button
                v-if="!isReferrer"
                type="primary"
                size="small"
                @click="handleEditLockedAmount"
              >
                조정
              </el-button>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="누적 수익">
            {{ userCoins.staking.totalRewardsNear.toFixed(4) }} NEAR
          </el-descriptions-item>
          <el-descriptions-item label="일일 수익률">
            {{ (userCoins.staking.dailyRewardRate * 100).toFixed(4) }}%
          </el-descriptions-item>
          <el-descriptions-item label="마지막 정산일" v-if="userCoins.staking.lastSettlementDate">
            {{ formatDate(userCoins.staking.lastSettlementDate) }}
          </el-descriptions-item>
        </el-descriptions>
        <el-empty v-else description="스테이킹 기록이 없습니다" />
      </div>
    </el-dialog>

    <!-- 锁仓金额调整对话框 -->
    <el-dialog
      v-model="lockedAmountDialogVisible"
      title="락정 금액 조정"
      width="500px"
    >
      <el-form v-if="selectedUser" label-width="120px">
        <el-form-item label="사용자">
          <span>{{ selectedUser.name }}</span>
        </el-form-item>
        <el-form-item label="현재 락정 금액">
          <span>{{ currentLockedAmount.toFixed(4) }} NEAR</span>
        </el-form-item>
        <el-form-item label="새로운 금액" required>
          <el-input-number
            v-model="newLockedAmount"
            :min="0"
            :precision="4"
            :step="1"
            style="width: 100%"
          />
          <div style="margin-top: 8px; color: #909399; font-size: 12px;">
            추천 보상으로 받은 NEAR 토큰의 락정 수량을 조정합니다
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="lockedAmountDialogVisible = false">취소</el-button>
        <el-button
          type="primary"
          :loading="adjusting"
          @click="confirmAdjustLockedAmount"
        >
          확인
        </el-button>
      </template>
    </el-dialog>

    <!-- 등급 변경 对话框 -->
    <el-dialog
      v-model="tierDialogVisible"
      title="등급 변경"
      width="500px"
    >
      <el-form v-if="selectedUser" label-width="120px">
        <el-form-item label="사용자">
          <span>{{ selectedUser.name }}</span>
        </el-form-item>
        <el-form-item label="현재 등급">
          <el-tag :type="getTierTagType(selectedUser.tier)">{{ selectedUser.tier }}</el-tag>
        </el-form-item>
        <el-form-item label="새로운 등급" required>
          <el-select v-model="newTier" placeholder="등급을 선택하세요" style="width: 100%">
            <el-option label="ENTRY" value="ENTRY" />
            <el-option label="BASIC" value="BASIC" />
            <el-option label="NORMAL" value="NORMAL" />
            <el-option label="ROYAL" value="ROYAL" />
            <el-option label="VIP" value="VIP" />
            <el-option label="VVIP" value="VVIP" />
          </el-select>
          <div style="margin-top: 8px; color: #909399; font-size: 12px;">
            등급 변경 시 즉시 적용되며, 현재 수익이 정산된 후 새로운 수익률로 계산됩니다
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="tierDialogVisible = false">취소</el-button>
        <el-button
          type="primary"
          :loading="changingTier"
          @click="confirmChangeTier"
        >
          확인
        </el-button>
      </template>
    </el-dialog>

    <!-- 입출금 기록 对话框 -->
    <el-dialog
      v-model="transactionsDialogVisible"
      title="입출금 기록"
      width="900px"
    >
      <div v-if="userTransactions && selectedUser">
        <h3>{{ selectedUser.name }}님의 거래 기록</h3>

        <el-tabs style="margin-top: 20px;">
          <el-tab-pane label="입금 기록">
            <el-table :data="userTransactions.deposits" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column label="금액" width="150">
                <template #default="{ row }">
                  {{ formatAmount(row.amount) }} KRW
                </template>
              </el-table-column>
              <el-table-column prop="status" label="상태" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="신청 시간" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="processedAt" label="처리 시간" width="180">
                <template #default="{ row }">
                  {{ row.processedAt ? formatDate(row.processedAt) : '-' }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="출금 기록">
            <el-table :data="userTransactions.withdraws" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column label="금액" width="150">
                <template #default="{ row }">
                  {{ formatAmount(row.amount) }} KRW
                </template>
              </el-table-column>
              <el-table-column prop="status" label="상태" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="신청 시간" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="processedAt" label="처리 시간" width="180">
                <template #default="{ row }">
                  {{ row.processedAt ? formatDate(row.processedAt) : '-' }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 用户信息编辑对话框 -->
    <el-dialog
      v-model="editInfoDialogVisible"
      title="사용자 정보 수정"
      width="500px"
    >
      <el-form v-if="selectedUser" label-width="120px">
        <el-form-item label="사용자">
          <span>{{ selectedUser.name }} ({{ selectedUser.idNumber }})</span>
        </el-form-item>
        <el-form-item label="새 비밀번호">
          <el-input
            v-model="editInfoForm.password"
            type="password"
            placeholder="변경하지 않으려면 비워 두세요"
            clearable
            show-password
          />
          <div style="margin-top: 4px; color: #909399; font-size: 12px;">
            최소 6자 이상
          </div>
        </el-form-item>
        <el-form-item label="계좌번호">
          <el-input
            v-model="editInfoForm.withdrawalAccount"
            placeholder="변경하지 않으려면 비워 두세요"
            clearable
          />
        </el-form-item>
        <el-form-item label="휴대전화">
          <el-input
            v-model="editInfoForm.mobileNumber"
            placeholder="변경하지 않으려면 비워 두세요"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editInfoDialogVisible = false">취소</el-button>
        <el-button
          type="primary"
          :loading="editingInfo"
          @click="confirmEditInfo"
        >
          저장
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { UserService } from '@/api/users'
import type { User, UserSearchParams, PaginationParams, UserCoins, UserTransactions } from '@/types/user'
import { UserStatus } from '@/types/user'
import { exportToExcel, formatAmount as formatAmountForExcel, formatDateTimeString } from '@/utils/exportExcel'
import type { ExportHeader } from '@/utils/exportExcel'
import request from '@/utils/request'

// 권한 판단: 추천인 로그인 여부 확인
const isReferrer = computed(() => {
  const userType = localStorage.getItem('admin_user_type')
  return userType === 'USER'
})

// 반응형 데이터
const loading = ref(false)
const isExporting = ref(false)
const userList = ref<User[]>([])
const selectedUser = ref<User | null>(null)
const detailDialogVisible = ref(false)

// 持有币对话框
const coinsDialogVisible = ref(false)
const userCoins = ref<UserCoins | null>(null)

// 锁仓金额调整对话框
const lockedAmountDialogVisible = ref(false)
const currentLockedAmount = ref(0)
const newLockedAmount = ref(0)
const adjusting = ref(false)

// 交易记录对话框
const transactionsDialogVisible = ref(false)
const userTransactions = ref<UserTransactions | null>(null)

// 等级变更对话框
const tierDialogVisible = ref(false)
const newTier = ref('')
const changingTier = ref(false)

// 用户信息编辑对话框
const editInfoDialogVisible = ref(false)
const editInfoForm = reactive({
  password: '',
  withdrawalAccount: '',
  mobileNumber: ''
})
const editingInfo = ref(false)

// 검색 폼
const searchForm = reactive({
  search: '',
  status: '' as UserStatus | ''
})

// 페이지네이션 데이터
const pagination = reactive<PaginationParams>({
  page: 1,
  limit: 20,
  total: 0,
  totalPages: 0
})

// 사용자 목록 로드
const loadUserList = async () => {
  try {
    loading.value = true
    const params: UserSearchParams = {
      page: pagination.page,
      limit: pagination.limit,
      search: searchForm.search.trim() || undefined,
      status: searchForm.status || undefined
    }

    const result = await UserService.getUserList(params)
    userList.value = result.users
    Object.assign(pagination, result.pagination)
  } catch (error) {
    console.error('회원 목록 로드 실패:', error)
    ElMessage.error('회원 목록을 불러오지 못했습니다')
  } finally {
    loading.value = false
  }
}

// Excel 내보내기
const handleExportExcel = async () => {
  try {
    isExporting.value = true

    // 构建导出参数（与当前筛选条件一致）
    const params: any = {
      exportAll: 'true', // 导出全部数据
      search: searchForm.search.trim() || undefined,
      status: searchForm.status || undefined
    }

    // 调用API获取全部数据
    const result = await UserService.getUserList(params)

    if (!result.users || result.users.length === 0) {
      ElMessage.warning('내보낼 데이터가 없습니다')
      return
    }

    // 定义导出的列
    const headers: ExportHeader[] = [
      { label: '추천 코드', prop: 'referralCode' },
      { label: '입장 코드', prop: 'entryCode' },
      { label: '이름', prop: 'name' },
      { label: '신분증', prop: 'idNumber' },
      { label: '생년월일 (6자리)', prop: 'birthDateFirst6' },
      { label: '은행', prop: 'withdrawalBank' },
      { label: '계좌번호', prop: 'withdrawalAccount' },
      { label: '휴대전화', prop: 'mobileNumber' },
      {
        label: '보유 금액 (₩)',
        prop: 'balance.total',
        formatter: (val) => formatAmountForExcel(val || 0)
      },
      {
        label: '상태',
        prop: 'status',
        formatter: (val) => getStatusText(val)
      },
      {
        label: '가입 일자',
        prop: 'createdAt',
        formatter: (val) => formatDateTimeString(val)
      },
      {
        label: '최후 로그인',
        prop: 'lastLoginAt',
        formatter: (val) => val ? formatDateTimeString(val) : '로그인 기록 없음'
      }
    ]

    // 导出Excel
    exportToExcel({
      fileName: '회원관리',
      headers,
      data: result.users,
      sheetName: '회원 목록'
    })

    ElMessage.success(`${result.users.length}건의 데이터를 성공적으로 내보냈습니다`)
  } catch (error) {
    console.error('Excel 내보내기 실패:', error)
    ElMessage.error('Excel 내보내기에 실패했습니다')
  } finally {
    isExporting.value = false
  }
}

// 검색 처리
const handleSearch = () => {
  pagination.page = 1
  loadUserList()
}

// 페이지 처리
const handlePageChange = (page: number) => {
  pagination.page = page
  loadUserList()
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  loadUserList()
}

// 정렬 처리
const handleSortChange = (sort: any) => {
  console.log('정렬 변경:', sort)
}

// 상세 보기
const handleViewDetail = async (user: User) => {
  try {
    const detail = await UserService.getUserDetail(user.id)
    selectedUser.value = detail
    detailDialogVisible.value = true
  } catch (error) {
    console.error('사용자 상세 조회 실패:', error)
    ElMessage.error('사용자 상세 정보를 불러오지 못했습니다')
  }
}

// 거래 기록 보기
const handleViewTransactions = (user: User) => {
  ElMessage.info(`${user.name}님의 거래 기록은 준비 중입니다.`)
}

// 查看持有币
const handleViewCoins = async (user: User) => {
  try {
    loading.value = true
    const coins = await UserService.getUserCoins(user.id)
    userCoins.value = coins
    selectedUser.value = user
    coinsDialogVisible.value = true
  } catch (error) {
    console.error('보유 코인 정보 조회 실패:', error)
    ElMessage.error('보유 코인 정보를 불러오지 못했습니다')
  } finally {
    loading.value = false
  }
}

// 打开编辑锁仓金额对话框
const handleEditLockedAmount = () => {
  if (userCoins.value?.staking) {
    currentLockedAmount.value = userCoins.value.staking.lockedAmount
    newLockedAmount.value = userCoins.value.staking.lockedAmount
  } else {
    currentLockedAmount.value = 0
    newLockedAmount.value = 0
  }
  lockedAmountDialogVisible.value = true
}

// 确认调整锁仓金额
const confirmAdjustLockedAmount = async () => {
  if (!selectedUser.value) return

  try {
    adjusting.value = true
    await UserService.adjustLockedAmount(selectedUser.value.id, newLockedAmount.value)
    ElMessage.success('락정 금액이 성공적으로 조정되었습니다')
    lockedAmountDialogVisible.value = false

    // 刷新持有币信息
    const coins = await UserService.getUserCoins(selectedUser.value.id)
    userCoins.value = coins
  } catch (error: any) {
    console.error('락업 금액 조정 실패:', error)
    ElMessage.error(error.message || '락정 금액 조정에 실패했습니다')
  } finally {
    adjusting.value = false
  }
}

// 查看入出金记录
const handleViewDepositWithdraw = async (user: User) => {
  try {
    loading.value = true
    const transactions = await UserService.getUserTransactions(user.id)
    userTransactions.value = transactions
    selectedUser.value = user
    transactionsDialogVisible.value = true
  } catch (error) {
    console.error('거래 기록 조회 실패:', error)
    ElMessage.error('입출금 기록을 불러오지 못했습니다')
  } finally {
    loading.value = false
  }
}

// 查看原本信息（复用详细信息）
const handleViewOriginal = (user: User) => {
  handleViewDetail(user)
}

// 打开等级变更对话框
const handleChangeTier = (user: User) => {
  selectedUser.value = user
  newTier.value = user.tier || 'ENTRY'
  tierDialogVisible.value = true
}

// 确认变更等级
const confirmChangeTier = async () => {
  if (!selectedUser.value) return

  if (newTier.value === selectedUser.value.tier) {
    ElMessage.warning('새 등급이 현재 등급과 동일합니다')
    return
  }

  try {
    await ElMessageBox.confirm(
      `"${selectedUser.value.name}" 사용자의 등급을 "${selectedUser.value.tier}"에서 "${newTier.value}"(으)로 변경하시겠습니까?\n\n변경 후:\n• 즉시 적용됩니다\n• 현재 수익이 정산됩니다\n• 새로운 수익률로 계산됩니다`,
      '등급 변경 확인',
      {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
        type: 'warning'
      }
    )

    changingTier.value = true

    // 使用 request 工具而不是原生 fetch
    await request.put(`/api/admin/users/${selectedUser.value.id}/tier`, {
      tier: newTier.value
    })

    ElMessage.success('등급이 성공적으로 변경되었습니다')
    tierDialogVisible.value = false
    loadUserList() // 刷新列表
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('등급 변경 실패:', error)
      ElMessage.error(error.message || '등급 변경에 실패했습니다')
    }
  } finally {
    changingTier.value = false
  }
}

// 사용자 상태 전환
const handleToggleStatus = async (user: User) => {
  const newStatus = user.status === UserStatus.ACTIVE ? UserStatus.SUSPENDED : UserStatus.ACTIVE
  const actionText = newStatus === UserStatus.ACTIVE ? '활성화' : '일시 중지'

  try {
    await ElMessageBox.confirm(
      `정말로 "${user.name}" 사용자를 ${actionText}하시겠습니까?`,
      '작업 확인',
      {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
        type: 'warning'
      }
    )

    await UserService.updateUserStatus(user.id, newStatus)
    ElMessage.success(`${actionText}가 완료되었습니다.`)
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`사용자 ${actionText} 실패:`, error)
      ElMessage.error(`${actionText}에 실패했습니다`)
    }
  }
}

// 사용자 삭제
const handleDeleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `⚠️ 위험한 작업 경고!\n\n"${user.name}" 사용자를 영구적으로 삭제합니다. 이 작업은:\n• 사용자의 모든 개인정보 삭제\n• 모든 입출금 기록 삭제\n• 모든 스테이킹 및 보상 기록 삭제\n• 모든 거래 내역 삭제\n• 추천 관계 해제\n\n이 작업은 되돌릴 수 없습니다. 계속하시겠습니까?`,
      '사용자 삭제 확인',
      {
        confirmButtonText: '삭제 확인',
        cancelButtonText: '취소',
        type: 'error',
        confirmButtonClass: 'el-button--danger',
        dangerouslyUseHTMLString: false
      }
    )

    // 최종 확인
    await ElMessageBox.confirm(
      `다시 한 번 확인합니다: 정말로 "${user.name}" 사용자를 삭제하시겠습니까?`,
      '최종 확인',
      {
        confirmButtonText: '삭제 확인',
        cancelButtonText: '취소',
        type: 'error'
      }
    )

    await UserService.deleteUser(user.id)
    ElMessage.success('사용자가 성공적으로 삭제되었습니다')
    loadUserList() // 목록 새로고침
  } catch (error) {
    if (error !== 'cancel') {
      console.error('사용자 삭제 실패:', error)
      ElMessage.error('사용자 삭제에 실패했습니다')
    }
  }
}

// 打开编辑信息对话框
const handleEditInfo = (user: User) => {
  selectedUser.value = user
  // 重置表单
  editInfoForm.password = ''
  editInfoForm.withdrawalAccount = user.withdrawalAccount || ''
  editInfoForm.mobileNumber = user.mobileNumber || ''
  editInfoDialogVisible.value = true
}

// 确认修改用户信息
const confirmEditInfo = async () => {
  if (!selectedUser.value) return

  // 验证至少修改一个字段
  const hasChanges =
    editInfoForm.password.trim() !== '' ||
    editInfoForm.withdrawalAccount !== selectedUser.value.withdrawalAccount ||
    editInfoForm.mobileNumber !== selectedUser.value.mobileNumber

  if (!hasChanges) {
    ElMessage.warning('수정된 정보가 없습니다')
    return
  }

  // 验证密码长度
  if (editInfoForm.password.trim() !== '' && editInfoForm.password.length < 6) {
    ElMessage.error('비밀번호는 최소 6자 이상이어야 합니다')
    return
  }

  try {
    editingInfo.value = true

    // 构建提交数据(只提交修改的字段)
    const updateData: any = {}

    if (editInfoForm.password.trim() !== '') {
      updateData.password = editInfoForm.password
    }

    if (editInfoForm.withdrawalAccount !== selectedUser.value.withdrawalAccount) {
      updateData.withdrawalAccount = editInfoForm.withdrawalAccount
    }

    if (editInfoForm.mobileNumber !== selectedUser.value.mobileNumber) {
      updateData.mobileNumber = editInfoForm.mobileNumber
    }

    await UserService.updateUserInfo(selectedUser.value.id, updateData)

    ElMessage.success('사용자 정보가 성공적으로 수정되었습니다')
    editInfoDialogVisible.value = false
    loadUserList() // 刷新列表
  } catch (error: any) {
    console.error('사용자 정보 수정 실패:', error)
    ElMessage.error(error.message || '사용자 정보 수정에 실패했습니다')
  } finally {
    editingInfo.value = false
  }
}

// 상세 대화상자 닫기
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  selectedUser.value = null
}

// 계좌 번호 포맷
const formatAccountNumber = (account: string) => {
  return `-- (${account.slice(-4)})`
}

// 금액 포맷
const formatAmount = (amount: number) => {
  return new Intl.NumberFormat('ko-KR').format(amount)
}

const formatDistributionProgress = (user: User): string => {
  if (!user.stakingProgress) {
    return '- / -'
  }
  const { dailyDistributionCount, totalSlots } = user.stakingProgress
  return `${dailyDistributionCount}/${totalSlots}`
}

const getDistributionPercentage = (user: User): number => {
  if (!user.stakingProgress || user.stakingProgress.totalSlots === 0) {
    return 0
  }
  const percentage = (user.stakingProgress.dailyDistributionCount / user.stakingProgress.totalSlots) * 100
  return Math.min(100, Math.round(percentage))
}

// 날짜 포맷
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 상태 태그 타입 반환
const getStatusTagType = (status: UserStatus) => {
  const types = {
    [UserStatus.ACTIVE]: 'success',
    [UserStatus.INACTIVE]: 'info',
    [UserStatus.SUSPENDED]: 'warning',
    [UserStatus.DELETED]: 'danger'
  }
  return types[status] || 'info'
}

// 상태 텍스트 반환
const getStatusText = (status: UserStatus) => {
  const texts = {
    [UserStatus.ACTIVE]: '정상',
    [UserStatus.INACTIVE]: '미활성',
    [UserStatus.SUSPENDED]: '일시 중지',
    [UserStatus.DELETED]: '삭제됨'
  }
  return texts[status] || status
}

// 获取状态标签类型（用于入出金记录）
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'COMPLETED': 'success',
    'PROCESSING': 'info'
  }
  return types[status] || 'info'
}

// 获取等级标签类型
const getTierTagType = (tier: string) => {
  const types: Record<string, string> = {
    'ENTRY': '',
    'BASIC': 'info',
    'NORMAL': 'success',
    'ROYAL': 'warning',
    'VIP': 'danger',
    'VVIP': 'danger'
  }
  return types[tier] || ''
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserList()
})
</script>

<style scoped lang="scss">
.page-container {
  padding: 24px;
  background-color: #f5f5f5;
}

.page-header {
  margin-bottom: 24px;

  h1 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0 0 8px 0;
  }

  p {
    font-size: 14px;
    color: #666;
    margin: 0;
  }
}

.page-content {
  .search-card {
    margin-bottom: 16px;

    .search-container {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .search-left {
        .search-label {
          font-weight: 500;
          color: #333;
        }
      }

      .search-right {
        .search-input {
          width: 400px;
        }
      }
    }
  }

  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 500;
      color: #333;
    }

    .account-info {
      font-size: 12px;

      .account-number {
        color: #666;
        margin-top: 2px;
      }
    }

    .distribution-progress {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .distribution-text {
        font-size: 12px;
        color: #606266;
        text-align: center;
      }
    }

    .text-muted {
      color: #909399;
      font-size: 12px;
    }

    .amount {
      font-family: 'Consolas', 'Monaco', monospace;
      font-weight: 500;
    }

    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}

.user-detail {
  :deep(.el-descriptions__body) {
    background-color: #fafafa;
  }
}

// 全局样式覆盖
:deep(.el-table) {
  font-size: 13px;

  .el-table__header {
    background-color: #f8f9fa;

    th {
      background-color: #f8f9fa !important;
      color: #666;
      font-weight: 500;
    }
  }

  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}

:deep(.el-button--small) {
  font-size: 12px;
  padding: 4px 8px;
}

:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}
</style>
